<template>
    <div class="captcha-container">
        <!-- 验证码图片 -->
        <img :src="`data:image/png;base64,${captchaData}`" alt="验证码" @click="fetchCaptcha" class="captcha-image"
            :class="{ 'refreshing': isLoading }" />


        <button v-if="showRefreshButton" @click="fetchCaptcha" class="refresh-button" :disabled="isLoading">
            {{ isLoading ? '刷新中...' : '刷新验证码' }}
        </button>
    </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';

// 定义触发事件
const emit = defineEmits(['update:sign']);

// 验证码数据
const captchaData = ref('');
// 加载状态
const isLoading = ref(false);
// 是否显示刷新按钮
const showRefreshButton = ref(true);

const sign= ref('')

// 获取验证码
const fetchCaptcha = async () => {
    try {
        isLoading.value = true;

        // 请求后端接口（根据实际情况修改URL）
        const response = await axios.post('http://localhost:8080/zhongjianyu.cat.com/api/user/captcha',{"1":1});
        console.log('获取验证码成功:', response.data);
        // 更新验证码数据
        captchaData.value = response.data.data.image;
        sign.value = response.data.data.sign;
        emit('update:sign', sign.value);  // 触发事件，将sign传递给父组件
    } catch (error) {
        console.error('获取验证码失败:', error);
        // 这里可以添加错误处理，比如显示错误提示
    } finally {
        isLoading.value = false;
    }
};

// 初始化时自动获取验证码
fetchCaptcha();
</script>

<style scoped>
.captcha-container {
    display: inline-flex;
    align-items: center;
    gap: 8px;
}

.captcha-image {
    cursor: pointer;
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 4px;
    transition: all 0.3s ease;

    /* 设置默认尺寸 */
    width: 120px;
    height: 40px;
    object-fit: contain;
}

.captcha-image.refreshing {
    opacity: 0.7;
    filter: grayscale(50%);
}

.refresh-button {
    padding: 4px 12px;
    background-color: #f0f0f0;
    border: 1px solid #ccc;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.refresh-button:hover:not(:disabled) {
    background-color: #e0e0e0;
}

.refresh-button:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}
</style>